<template>
	<!-- 欢迎启动页 -->
	<view v-if="showWelcome" class="ai-start">
		<view class="start-hero">
			<image class="logo" src="/static/favicon.ico" mode="widthFix"></image>
		</view>
		<view class="start-text">
			<text class="greeting">嘿！我是AI医生，我将指导您分析可能出现的医疗症状。你准备好了吗？</text>
		</view>
		<view class="start-actions">
			<button class="btn btn-primary" @click="startFromWelcome">是的，开始 →</button>
			<button class="btn btn-danger" @click="cancelWelcome">不，结束吧 ×</button>
		</view>
	</view>

	<view v-else class="chat-container">
		<!-- 顶部导航栏 -->
		<view class="chat-header">
			<text class="header-title">云诊康医疗助手</text>
		</view>
		
		<!-- 功能入口卡片 -->
		<view class="feature-cards">
			<view class="card" @click="goSymptom">
				<image class="card-img" src="/static/images/banner/banner02.jpg" mode="aspectFill"></image>
				<view class="card-title">AI问诊</view>
				<view class="card-sub">智能自测 · 症状分析</view>
			</view>
			<view class="card" @click="goHealth">
				<image class="card-img" src="/static/images/nice/new2.jpg" mode="aspectFill"></image>
				<view class="card-title">健康咨询</view>
				<view class="card-sub">健康知识 · 在线咨询</view>
			</view>
		</view>
		
		<!-- 聊天消息列表 -->
		<scroll-view 
			class="chat-messages" 
			scroll-y="true" 
			:scroll-top="scrollTop"
			scroll-with-animation="true"
		>
			<view class="message-list">
				<!-- 欢迎消息 -->
				<view v-if="messages.length === 0" class="welcome-message">
					<view class="ai-message">
						<view class="avatar ai-avatar">
							<text class="iconfont icon-robot"></text>
						</view>
						<view class="message-content ai-content">
							<text>您好！我是云诊康医疗助手，有什么健康问题可以咨询我。</text>
						</view>
					</view>
				</view>
				
				<!-- 消息列表 -->
				<view v-for="(message, index) in messages" :key="index" class="message-item">
					<!-- 用户消息 -->
					<view v-if="message.type === 'user'" class="user-message">
						<view class="message-content user-content">
							<text>{{ message.content }}</text>
						</view>
						<view class="avatar user-avatar">
							<text class="iconfont icon-user"></text>
						</view>
					</view>
					
					<!-- AI消息 -->
					<view v-else class="ai-message">
						<view class="avatar ai-avatar">
							<text class="iconfont icon-robot"></text>
						</view>
						<view class="message-content ai-content">
							<text>{{ message.content }}</text>
							<view v-if="message.loading" class="typing-indicator">
								<text class="dot"></text>
								<text class="dot"></text>
								<text class="dot"></text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 输入区域 -->
		<view class="chat-input">
			<view class="input-wrapper">
				<input 
					class="message-input"
					v-model="inputMessage"
					placeholder="请输入您的问题..."
					:disabled="isLoading"
					@confirm="sendMessage"
					confirm-type="send"
				/>
				<button 
					class="send-btn"
					:class="{ 'disabled': !inputMessage.trim() || isLoading }"
					@click="sendMessage"
					:disabled="!inputMessage.trim() || isLoading"
				>
					<text v-if="!isLoading" class="iconfont icon-send"></text>
					<text v-else class="loading-text">发送中</text>
				</button>
			</view>
		</view>
	</view>
</template>

<script>
import { chatWithAI } from '@/api/ai'

export default {
	data() {
		return {
			showWelcome: true,
			messages: [],
			inputMessage: '',
			isLoading: false,
			scrollTop: 0,
			streamingMessage: null,
		}
	},
	onLoad() {
		// 页面加载时的初始化
		this.initChat();
	},
	onShow() {
		// 每次从其他tab进入AI助手，都先展示欢迎页
		this.showWelcome = true
	},
	
	methods: {
		// 启动页按钮
		startFromWelcome() {
			this.goSymptom()
		},
		cancelWelcome() {
			// 返回首页tab
			uni.switchTab({ url: '/pages/index' })
		},
		// 顶部入口跳转
		goSymptom() {
			// 调试提示，确认点击有触发
			uni.showToast({ title: '打开AI问诊聊天...', icon: 'none', duration: 800 })
			// 跳转到AI问诊聊天页
			uni.switchTab({
				url: '/pages/consult/ai',
				success() { console.log('switchTab 成功: /pages/consult/ai') },
				fail(err) { console.error('switchTab 失败: /pages/consult/ai', err); uni.showToast({ title: '页面打开失败', icon: 'none' }) }
			})
		},
		goHealth() {
			// 若后续有更具体的健康咨询页，可替换为对应地址
			uni.showToast({ title: '打开健康咨询...', icon: 'none', duration: 800 })
			uni.navigateTo({
				url: '/pages/consult/health',
				success() { console.log('navigateTo 成功: /pages/consult/health') },
				fail(err) { console.error('navigateTo 失败: /pages/consult/health', err); uni.showToast({ title: '页面打开失败', icon: 'none' }) }
			})
		},
		// 初始化聊天
		initChat() {
			
		},
		
		// 发送消息
		async sendMessage() {
			if (!this.inputMessage.trim() || this.isLoading) {
				return;
			}
			
			const userMessage = this.inputMessage.trim();
			this.inputMessage = '';
			
			// 添加用户消息
			this.messages.push({
				type: 'user',
				content: userMessage,
				timestamp: new Date()
			});
			
			// 添加AI消息占位符
			const aiMessageIndex = this.messages.length;
			this.messages.push({
				type: 'ai',
				content: '',
				loading: true,
				timestamp: new Date()
			});
			
			this.isLoading = true;
			this.scrollToBottom();
			
			try {
				await this.sendChatRequest(userMessage, aiMessageIndex);
			} catch (error) {
				console.error('发送消息失败:', error);
				this.messages[aiMessageIndex] = {
					type: 'ai',
					content: '抱歉，服务暂时不可用，请稍后再试。',
					loading: false,
					timestamp: new Date()
				};
			} finally {
				this.isLoading = false;
			}
		},
		
		// 发送聊天请求（流式响应）
		async sendChatRequest(message, messageIndex) {
			try {
				console.log("开始获取响应，消息内容:", message);
				// 使用封装的API接口，传递clientId
				const response = await chatWithAI(message);
				console.log("响应获取成功", response);
				
				// 处理响应数据
				if (response) {
					if (response.data) {
						this.handleStreamResponse(response.data, messageIndex);
					} else if (response.code === 200) {
						// 可能响应直接是文本内容
						this.handleStreamResponse(response, messageIndex);
					} else {
						throw new Error('响应数据为空或格式错误');
					}
				} else {
					throw new Error('响应数据为空');
				}
			} catch (error) {
				console.error('API请求失败:', error);
				throw error;
			}
		},
		
		// 处理流式响应
		handleStreamResponse(data, messageIndex) {
			console.log('收到响应数据:', data);
			
			// 检查响应数据格式
			if (typeof data === 'string') {
				// 直接是文本响应
				this.displayResponse(data, messageIndex);
			} else if (data && typeof data === 'object') {
				// 可能是包装的响应对象
				const responseText = data.data || data.content || data.message || JSON.stringify(data);
				this.displayResponse(responseText, messageIndex);
			} else {
				console.error('未知的响应数据格式:', data);
				this.messages[messageIndex] = {
					type: 'ai',
					content: '抱歉，响应数据格式异常。',
					loading: false,
					timestamp: new Date()
				};
			}
		},
		
		// 显示响应内容（带打字机效果）
		displayResponse(fullResponse, messageIndex) {
			if (!fullResponse || typeof fullResponse !== 'string') {
				this.messages[messageIndex] = {
					type: 'ai',
					content: '抱歉，响应内容为空。',
					loading: false,
					timestamp: new Date()
				};
				return;
			}
			
			let currentIndex = 0;
			
			const typeWriter = () => {
				if (currentIndex < fullResponse.length) {
					this.messages[messageIndex].content = fullResponse.substring(0, currentIndex + 1);
					currentIndex++;
					this.scrollToBottom();
					setTimeout(typeWriter, 30); // 打字机效果速度
				} else {
					this.messages[messageIndex].loading = false;
					this.scrollToBottom();
				}
			};
			
			// 开始打字机效果
			this.messages[messageIndex].loading = false;
			typeWriter();
		},
		
		// 滚动到底部
		scrollToBottom() {
			this.$nextTick(() => {
				this.scrollTop = 99999;
			});
		},
		
		// 清空聊天记录
		clearChat() {
			uni.showModal({
				title: '确认清空',
				content: '确定要清空所有聊天记录吗？',
				success: (res) => {
					if (res.confirm) {
						this.messages = [];
					}
				}
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.ai-start {
  position: relative;
  min-height: 100vh;
  background: #ffffff;
  padding: 40rpx 40rpx calc(40rpx + env(safe-area-inset-bottom));
  display: flex;
  flex-direction: column;
}
.start-hero {
  margin-top: 20rpx;
  .logo { width: 96rpx; height: 96rpx; border-radius: 20rpx; }
}
.start-text {
  margin-top: 30rpx;
  .greeting {
    display: block;
    font-size: 36rpx;
    font-weight: 700;
    color: #1f2937;
    line-height: 1.6;
  }
}
.start-actions {
  margin-top: 120rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 24rpx;
  .btn {
    width: 380rpx;
    height: 92rpx;
    line-height: 92rpx;
    border-radius: 999rpx;
    font-size: 30rpx;
    font-weight: 600;
    border: 2rpx solid transparent;
    text-align: center;
    padding: 0;
  }
  .btn-primary {
    background: linear-gradient(135deg, #10b981, #06b6d4);
    color: #ffffff;
    box-shadow: 0 10rpx 24rpx rgba(16,185,129,0.25);
  }
  .btn-danger {
    background: linear-gradient(135deg, #fb7185, #ef4444);
    color: #ffffff;
    box-shadow: 0 10rpx 24rpx rgba(239,68,68,0.25);
  }
}

/* 移除小程序默认描边，避免按钮尺寸偏移 */
.start-actions .btn::after { border: none; }

.chat-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f5f5;
}

/* 顶部功能入口卡片样式 */
.feature-cards {
	display: grid;
	grid-template-columns: 1fr 1fr;
	gap: 20rpx;
	padding: 20rpx;
}
.card { background: #ffffff; border-radius: 16rpx; padding: 16rpx; box-shadow: 0 6rpx 20rpx rgba(0,0,0,0.04); text-align: center; }
.card-img { width: 100%; height: 160rpx; border-radius: 12rpx; }
.card-title { margin-top: 10rpx; font-weight: 600; font-size: 30rpx; }
.card-sub { margin-top: 4rpx; color: #888; font-size: 24rpx; }

.chat-header {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	padding: 20rpx 30rpx;
	padding-top: calc(20rpx + var(--status-bar-height, 0));
	
	.header-title {
		color: white;
		font-size: 36rpx;
		font-weight: 600;
		text-align: center;
		display: block;
		margin-bottom: 10rpx;
	}
	
}

.chat-messages {
	flex: 1;
	padding: 20rpx;
	overflow-y: auto;
}

.message-list {
	padding-bottom: 20rpx;
}

.welcome-message,
.message-item {
	margin-bottom: 30rpx;
}

.user-message,
.ai-message {
	display: flex;
	align-items: flex-start;
	gap: 20rpx;
}

.user-message {
	flex-direction: row-reverse;
	
	.message-content {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
		margin-left: 80rpx;
	}
}

.ai-message {
	.message-content {
		background: white;
		color: #333;
		margin-right: 80rpx;
		border: 2rpx solid #e8e8e8;
	}
}

.avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 32rpx;
	flex-shrink: 0;
}

.user-avatar {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
}

.ai-avatar {
	background: #f0f0f0;
	color: #666;
	border: 2rpx solid #e8e8e8;
}

.message-content {
	max-width: 500rpx;
	padding: 20rpx 30rpx;
	border-radius: 20rpx;
	font-size: 28rpx;
	line-height: 1.5;
	word-wrap: break-word;
	position: relative;
}

.typing-indicator {
	display: flex;
	gap: 8rpx;
	margin-top: 10rpx;
	
	.dot {
		width: 8rpx;
		height: 8rpx;
		background-color: #999;
		border-radius: 50%;
		animation: typing 1.4s infinite;
		
		&:nth-child(2) {
			animation-delay: 0.2s;
		}
		
		&:nth-child(3) {
			animation-delay: 0.4s;
		}
	}
}

@keyframes typing {
	0%, 60%, 100% {
		transform: translateY(0);
		opacity: 0.4;
	}
	30% {
		transform: translateY(-10rpx);
		opacity: 1;
	}
}

.chat-input {
	background: white;
	padding: 20rpx 30rpx;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	border-top: 2rpx solid #e8e8e8;
}

.input-wrapper {
	display: flex;
	align-items: center;
	gap: 20rpx;
	background: #f8f8f8;
	border-radius: 50rpx;
	padding: 10rpx 20rpx;
}

.message-input {
	flex: 1;
	height: 70rpx;
	font-size: 28rpx;
	background: transparent;
	border: none;
	outline: none;
}

.send-btn {
	width: 70rpx;
	height: 70rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: white;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	transition: all 0.3s ease;
	
	&.disabled {
		background: #ccc;
		color: #999;
	}
	
	.loading-text {
		font-size: 20rpx;
	}
}

// 图标字体样式（需要引入iconfont）
.iconfont {
	font-family: "iconfont";
}

// 响应式适配
@media screen and (max-width: 750rpx) {
	.message-content {
		max-width: 400rpx;
	}
}
</style>